package com.hostmanagement.user;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.hostmanagement.util.db.DBUtil;
import com.hostmanagement.util.encrypt.StringUtils;

public class UserManage {

	/**
	 * Used to check if the new userName has existed.
	 * 
	 * @param userName
	 * @return
	 * @throws SQLException
	 */
	public boolean isUserExist(String userName) throws Exception {
		Connection con = null;
		Statement stmt = null;
		try {
			String check_user_sql = "select 1 from user_info where user_name='"
					+ userName + "'";
			con = DBUtil.getConnection();
			stmt = con.createStatement();

			ResultSet rs = stmt.executeQuery(check_user_sql);
			if (rs.next()) {
				return true;
			}
		} catch (SQLException e) {
			throw e;
		}

		return false;
	}

	/**
	 * Add user
	 * @param user
	 * @return
	 * @throws Exception
	 */
	public void addUser(UserBean user) throws Exception {

		Connection con = null;
		Statement stmt = null;
		try {
			int autoIncKeyFromApi = -1;

			Date regTime = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String sql1 = "insert into user_info(user_name,user_password,reg_time,rule_id,dog_id) values('"
					+ user.getUserName()
					+ "','"
					+ StringUtils.encrypt(user.getUserPassword())
					+ "','"
					+ sdf.format(regTime)
					+ "',"
					+ user.getRuleId()
					+ ",'" + user.getDogId() + "')";

			con = DBUtil.getConnection();
			stmt = con.createStatement();

			stmt.executeUpdate(sql1, Statement.RETURN_GENERATED_KEYS);
			ResultSet rs = stmt.getGeneratedKeys();
			if (rs.next()) {
				autoIncKeyFromApi = rs.getInt(1);
			}

			String sql2 = "insert into user_detail_info(user_id,real_name,sex,birthday,accont_id,phone1,phone2,mobile,email,address,remark) values("
					+ autoIncKeyFromApi
					+ ",'"
					+ user.getRealName()
					+ "','"
					+ user.getSex()
					+ "','"
					+ user.getBirthday()
					+ "','"
					+ user.getAccontId()
					+ "','"
					+ user.getPhone1()
					+ "','"
					+ user.getPhone2()
					+ "','"
					+ user.getMobile()
					+ "','"
					+ user.getEmail()
					+ "','"
					+ user.getAddress()
					+ "','"
					+ user.getRemark()
					+ "')";

			stmt.execute(sql2);

		} catch (SQLException e) {
			throw e;
		} finally {
			try {
				if (stmt != null)
					stmt.close();
				if (con != null)
					con.close();
			} catch (Exception e1) {
				throw e1;
			}
		}
	}

}
